﻿using System;
using System.Collections.Generic;
using System.Text;

namespace UdpReceive
{
    /// <summary>
    /// 接收数据模型
    /// </summary>
    [Serializable]
    public class SendCell : IDataCell
    {
        /// <summary>
        /// CRC检验状态
        /// </summary>
        private bool _checkCrc;
        public bool CheckCrc
        {
            get { return _checkCrc; }
            set { _checkCrc = value; }
        }
        /// <summary>
        /// 请求命令
        /// </summary>
        private int _orderID;
        public int OrderID
        {
            get { return _orderID; }
            set { _orderID = value; }
        }
        /// <summary>
        /// 校验码
        /// </summary>
        private string _crc;
        public string CRC
        {
            get { return _crc; }
            set { _crc = value; }
        }
        /// <summary>
        /// 接收源数据数组
        /// </summary>
        private byte[] _sourceData;
        public byte[] SourceData
        {
            get { return _sourceData; }
            set { _sourceData = value; }
        }
        private string _data;
        public string Data
        {
            get { return _data; }
            set { _data = value; }
        }

        public SendCell() { }

        public SendCell(
            int orderID,
            string data)
        {
            _orderID = orderID;
            _data = data;
        }
        /// <summary>
        /// 解析接收数据
        /// </summary>
        /// <param name="buffer"></param>
        public void FromBuffer(byte[] buffer)
        {
            _sourceData = buffer;
            //CRC校验
            byte[] crc;
            _checkCrc = CRCUtility.CheckCRC(ref buffer, buffer.Length,out crc);
            _crc = DataUtility.ByteArrayToHexString(crc,crc.Length);
            //客户端CRC十六进制显示
            byte[] rData = new byte[2];
            Array.Copy(buffer, buffer.Length - 2, rData, 0, 2);
            string cCRCStr = DataUtility.ByteArrayToHexString(rData, 2);
            //客户端内容
            _data = Encoding.Default.GetString(buffer, 0, buffer.Length - 2) + cCRCStr;//Encoding.ASCII
            if (_checkCrc && buffer != null && buffer.Length > 10)
            {
                _data = Encoding.Default.GetString(buffer, 0, 10);
                switch (_data)
                {
                    case "***TERLIST":
                        _orderID = Int32.Parse("1");
                        break;
                    case "***UPLOADF":
                        _orderID = Int32.Parse("2");
                        break;
                    case "***GETTEIP":
                        _orderID = Int32.Parse("3");
                        break;
                    default:
                        _orderID = Int32.Parse("0");
                        break;
                }
            }
        }
    }
}
